﻿using System.Data;

using Autofac;

using Cookbook.Services.Core.Persistency;
using Cookbook.Services.Core.Persistency.Common;
using Cookbook.Services.Core.Persistency.NHibernate;

using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace Cooking.Services.Specs.Persistency
{
    internal class SqlLiteUnitOfWorkFactory : CookbookUnitOfWorkFactory
    {
        private readonly ILifetimeScope lifetimeScope;

        public SqlLiteUnitOfWorkFactory(ILifetimeScope lifetimeScope) : base(lifetimeScope)
        {
            this.lifetimeScope = lifetimeScope;
        }

        protected override CookbookUnitOfWork CreateUnitOfWork(IDataMapper mapper)
        {
            return new CookbookUnitOfWork(mapper);
        }

        protected override IDataMapper CreateDataMapper()
        {
            var mapper = base.CreateDataMapper() as NHibernateDataMapper;

            GenerateSchema(mapper);

            return mapper;
        }

        private void GenerateSchema(NHibernateDataMapper mapper)
        {
            IDbConnection connection = mapper.Session.Connection;
            var config = lifetimeScope.Resolve<Configuration>();

            new SchemaExport(config).Execute(false, true, false, connection, null);
        }
    }
}